package com.xlr.excel.queue;

import com.google.common.collect.MapMaker;
import com.xlr.excel.entity.SourseVehicle;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @Author: xlr
 * @Date: Created in 下午7:37 2019/3/3
 */
@Component
public class QueueHander {

    public void sendQueue(SourseVehicle obj ){
        getQueue("sv").add( obj );
    }

    public SourseVehicle getTask(){
        SourseVehicle take = null;
        try {
            take = (SourseVehicle) getQueue("sv").take();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return take;
    }

    @SuppressWarnings("rawtypes")
    private static ConcurrentMap<String, BlockingQueue> queueMap = new MapMaker().concurrencyLevel(32).makeMap();//消息队列

    private static int queueSize = Integer.MAX_VALUE;

    /**
     * 根据queueName获得消息队列的静态函数.
     * 如消息队列还不存在, 会自动进行创建.
     */
    public static <T> BlockingQueue<T> getQueue(String queueName) {
        BlockingQueue<T> queue = queueMap.get(queueName);

        if (queue == null) {
            BlockingQueue<T> newQueue = new LinkedBlockingQueue<T>(queueSize);

            //如果之前消息队列还不存在,放入新队列并返回Null.否则返回之前的值.
            queue = queueMap.putIfAbsent(queueName, newQueue);
            if (queue == null) {
                queue = newQueue;
            }
        }
        return queue;
    }

}
